package com.rock.code.system.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rock.code.base.controller.BaseController;
import com.rock.code.base.domain.AjaxJson;
import com.rock.code.base.domain.Constants;
import com.rock.code.common.comm.DesEncrypterIsmp;
import com.rock.code.common.excel.ExportExcel;
import com.rock.code.common.exceptions.SystemException;
import com.rock.code.common.pager.Page;
import com.rock.code.system.user.domain.TbSysLoginmsg;
import com.rock.code.system.user.service.TbSysLoginmsgService;
import com.rock.code.system.userRole.domain.TbSysUserRole;
import com.rock.code.system.userRole.service.impl.TbSysUserRoleServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author piandu
 * @date 2018 /05/11
 */
@Controller
@RequestMapping("/tbSysLoginmsg")
public class TbSysLoginmsgController extends BaseController {

    /**
    * The tbSysLoginmsgServiceImpl
    */
    @Resource
    private TbSysLoginmsgService tbSysLoginmsgServiceImpl;

    @Resource
    private TbSysUserRoleServiceImpl tbSysUserRolesServiceImpl;

    /**
     * Dispatch.
     *
     * @return the string
     * @throws Exception the exception
     * @author piandu
     * @date 2018 /05/11
     */
    @RequestMapping("")
    public String dispatch() throws Exception {
        return "system/user/tbSysLoginmsg";
    }

    /**
     * queryPageList
     *
     * @return the page info
     * @throws Exception the exception
     * @author piandu
     * @date 2018 /05/11
     */
    @ResponseBody
    @RequestMapping(value = "/queryPageList", method = RequestMethod.POST)
    public PageInfo<TbSysLoginmsg> queryPageList() throws Exception {
        Map<String, Object> param = this.getRequestMapSingle();
        Page page = new Page(request);
        PageInfo pageInfo = null;
        try {
            param.put("isDelete", Constants.DELETE_N);
            pageInfo = tbSysLoginmsgServiceImpl.queryPageList(page, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return pageInfo;
    }

    /**
     * querySingle
     *
     * @return TbSysLoginmsg tb sys loginmsg
     * @throws Exception the exception
     * @author piandu
     * @date 2018 /05/11
     */
    @ResponseBody
    @RequestMapping(value = "/querySingle", method = RequestMethod.POST)
    public TbSysLoginmsg querySingle() throws Exception {
        Map<String, Object> param = this.getRequestMapSingle();
        param.put("isDelete",Constants.DELETE_N);
        TbSysLoginmsg tbSysLoginmsg = null;
        try {
            tbSysLoginmsg = tbSysLoginmsgServiceImpl.queryByParaMap(param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return tbSysLoginmsg;
    }

    /**
    * Save.
    *
    * @param tbSysLoginmsg the TbSysLoginmsg
    * @return the ajax json
    * @throws Exception the exception
    * @author piandu
    * @date 2018/05/11
    */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxJson save(@RequestBody TbSysLoginmsg tbSysLoginmsg) throws Exception {
        try {
            // 设置默认字段
            tbSysLoginmsg.setDeptId(tbSysLoginmsg.getDeptCode());
            tbSysLoginmsg.setLoginState(0l);
            tbSysLoginmsg.setLockstate("0");
            tbSysLoginmsg.setIsVip("0");
            tbSysLoginmsg.setIsEnable(1);

            TbSysLoginmsg sessionUser = getSessionUser();
            if (isNotEmpty(tbSysLoginmsg.getLoginId())) {
                tbSysLoginmsg.setModifier(sessionUser.getLoginId());
                tbSysLoginmsg.setModifieDate(new Date());
                tbSysLoginmsgServiceImpl.update(tbSysLoginmsg);
            } else {
                // 其它操作
                tbSysLoginmsg.setLoginPasswd(DesEncrypterIsmp.encrypt(tbSysLoginmsg.getLoginCode()));
                tbSysLoginmsg.setIsDelete(Constants.DELETE_N);
                tbSysLoginmsg.setIsFrozen(Constants.FROZEN_N);
                tbSysLoginmsg.setCreater(sessionUser.getLoginCode());
                tbSysLoginmsg.setCreateDate(new Date());
                tbSysLoginmsg.setModifier(sessionUser.getLoginCode());
                tbSysLoginmsg.setModifieDate(new Date());

                tbSysLoginmsgServiceImpl.insert(tbSysLoginmsg);
            }
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
     * Save.
     *
     * @return the ajax json
     * @throws Exception the exception
     * @author wangwenbo
     * @date 2018.2.9
     */
    @ResponseBody
    @RequestMapping(value = "/saveUserRoles", method = RequestMethod.POST)
    public AjaxJson saveUserRoles() throws Exception {
        try {
            TbSysLoginmsg sessionUser = getSessionUser();
            Map<String, Object> params = this.getRequestMapSingle();
            Map<String, Object> loginCode = new HashMap<String, Object>();
            Map<String, String[]> functionRoles = new HashMap<String, String[]>();
            Map<String, String[]> dataRoles = new HashMap<String, String[]>();

            loginCode.put("loginCode", params.get("loginCode"));
            loginCode.put("isDelete", Constants.DELETE_N);
            String functionRolesStr = (String) params.get("functionRoles");
            String dataRolesStr = (String) params.get("dataRoles");
            functionRoles.put("roleCode", functionRolesStr.split(","));
            dataRoles.put("dataroleCode", dataRolesStr.split(","));
            // 删除原功能权限
            List<TbSysUserRole> tbSysUserRoles = tbSysUserRolesServiceImpl.queryListByParaMap(loginCode);
            for (TbSysUserRole role : tbSysUserRoles){
                role.setIsDelete(Constants.DELETE_Y);
                role.setModifier(sessionUser.getName());
                role.setModifieDate(new Date());
                tbSysUserRolesServiceImpl.update(role);
            }

            // 赋予新功能权限
            for (String roleCode : functionRoles.get("roleCode")) {
                if (isNotEmpty(roleCode)){
                    TbSysUserRole tbSysUserRoles1 = new TbSysUserRole();
                    tbSysUserRoles1.setLoginCode((String) loginCode.get("loginCode"));
                    tbSysUserRoles1.setRoleCode(roleCode);
                    tbSysUserRoles1.setIsDelete(Constants.DELETE_N);
                    tbSysUserRoles1.setCreater(sessionUser.getName());
                    tbSysUserRoles1.setCreateDate(new Date());
                    tbSysUserRoles1.setModifier(sessionUser.getName());
                    tbSysUserRoles1.setModifieDate(new Date());
                    tbSysUserRolesServiceImpl.insert(tbSysUserRoles1);
                }

            }
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }
    /**
    * Delete.
    *
    * @param ids the ids
    * @return the ajax json
    * @throws Exception the exception
    * @author piandu
    * @date 2018/05/11
    */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxJson delete(@RequestParam String ids) throws Exception {
        try {
            String[] loginIds = ids.split(",");
            TbSysLoginmsg sessionUser = getSessionUser();
            for (String loginId : loginIds) {
                TbSysLoginmsg tbSysLoginmsg = new TbSysLoginmsg();
                tbSysLoginmsg.setLoginId(loginId);
                tbSysLoginmsg.setIsDelete(Constants.DELETE_Y);
                tbSysLoginmsg.setModifier(sessionUser.getLoginCode());
                tbSysLoginmsg.setModifieDate(new Date());
                tbSysLoginmsgServiceImpl.update(tbSysLoginmsg);
            }
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
     * Reset password.
     *
     * @return the ajax json
     * @throws Exception the exception
     * @author wangwenbo
     * @date 2018.01.11
     */
    @ResponseBody
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public AjaxJson resetPassword() throws Exception {
        Map<String, Object> params = this.getRequestMapSingle();

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("loginId", params.get("loginId"));
        param.put("isDelete", Constants.DELETE_N);
        String loginPasswd = DesEncrypterIsmp.encrypt((String) params.get("loginPasswd"));
        TbSysLoginmsg sessionUser = getSessionUser();
        TbSysLoginmsg tbSysLoginmsg = null;
        try {
            tbSysLoginmsg = tbSysLoginmsgServiceImpl.queryByParaMap(param);
            tbSysLoginmsg.setLoginPasswd(loginPasswd);
            tbSysLoginmsg.setIsDelete(Constants.DELETE_N);
            tbSysLoginmsg.setCreater(sessionUser.getLoginCode());
            tbSysLoginmsg.setCreateDate(new Date());
            tbSysLoginmsg.setModifier(sessionUser.getLoginCode());
            tbSysLoginmsg.setModifieDate(new Date());
            tbSysLoginmsgServiceImpl.update(tbSysLoginmsg);
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
     * Reset password.
     *
     * @return the ajax json
     * @throws Exception the exception
     * @author wangwenbo
     * @date 2018.01.11
     */
    @ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public AjaxJson updatePassword() throws Exception {
        try {
            Map<String, Object> params = this.getRequestMapSingle();
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("loginId", params.get("loginId"));
            param.put("loginPasswd", DesEncrypterIsmp.encrypt((String)params.get("loginPasswd")));
            param.put("prePassword", DesEncrypterIsmp.encrypt((String)params.get("prePassword")));
            param.put("isDelete", Constants.DELETE_N);
            tbSysLoginmsgServiceImpl.updatePassword(param);
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
    * Exp excel.
    *
    * @return the ajax json
    * @throws Exception the exception
    * @author piandu
    * @date 2018/05/11
    */
    @ResponseBody
    @RequestMapping(value = "/expExcel", method = RequestMethod.POST)
    public AjaxJson expExcel() throws Exception {
        try {
            Map<String, Object> param = this.getRequestMapSingle();
            String[] titles = (String[]) param.get("titles[]");
            String[] fields = (String[]) param.get("fields[]");
            Page page = new Page((String) param.get("sidx"), (String) param.get("sord"));
            param.put("isDelete", Constants.DELETE_N);
            ExportExcel ee = new ExportExcel();
            List rows = tbSysLoginmsgServiceImpl.queryListByOrder(page, param);
            String path = ee.exportExcel(request, response, 40000, titles, fields, rows, TbSysLoginmsg.class.getName());
            ajaxJson.setResult(path);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return ajaxJson;
    }

    /**
     * Check input field.
     *
     * @return the json object
     * @throws Exception the exception
     * @author kongqiang
     * @date 2018.01.03
     */
    @ResponseBody
    @RequestMapping(value = "/checkInputField", method = RequestMethod.POST)
    public JSONObject checkInputField() throws Exception {
        try {
            Map<String, Object> param = this.getRequestMapSingle();
            param.put("isDelete", Constants.DELETE_N);
            String loginPasswd = (String) param.get("loginPasswd");
            if (loginPasswd != null){
                param.remove("loginPasswd");
                param.put("loginPasswd", DesEncrypterIsmp.encrypt(loginPasswd));
            }
            List rows = tbSysLoginmsgServiceImpl.queryListByParaMap(param);
            if (loginPasswd != null){
                if (rows != null && rows.size() > 0) {
                    json.put("valid", true);
                } else {
                    json.put("valid", false);
                }
            } else {
                if (rows != null && rows.size() > 0) {
                    json.put("valid", false);
                } else {
                    json.put("valid", true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return json;
    }
}
